package components.scenes;

import java.util.LinkedList;

import components.CollisionableComponent;
import components.direction.Direction;
import components.terrain.Terrain;

public class MapMatrix {

	private Slot[][] elems;
	
	private int width;
	private int height;
	
	public MapMatrix(int width, int height){
		this.width = width;
		this.height = height;
		this.elems = new Slot[width][height];
		this.initSlots();
	}
	
	private void initSlots() {
		for (int i = 0; i < width ; i++){
			for (int ii = 0; ii < height; ii++){
				elems[i][ii] = new Slot(i, ii);
			}
		}
	}

	public void setTerrain(int xs, int ys, Terrain terrain){
		terrain.setX(xs* Slot.DIAMETER);
		terrain.setY(ys* Slot.DIAMETER); 
		this.elems[xs][ys].setTerrain(terrain);
	}

	public Slot slot(int x, int y){
		return this.elems[x][y];
	}
	
	public Slot nextSlot(Slot currentSlot, Direction dir) {
		return this.slot(currentSlot.getX() + dir.getVx(), currentSlot.getY() + dir.getVy());
	}

	public void centerComponentOnSlot(CollisionableComponent cc, int xslot, int yslot) {
		cc.centerOn(xslot* Slot.DIAMETER + Slot.DIAMETER/2, yslot* Slot.DIAMETER + Slot.DIAMETER/2);
		
	}

	public Slot nextSlot(int x, int y, Direction dir) {
		return this.slot(x + dir.getVx(), y + dir.getVy());
	}

	public LinkedList<Slot> sourroundingPaths(Slot slot) {
		LinkedList<Slot> slots = new LinkedList<Slot>();
		
		if (this.nextSlot(slot, Direction.NORTH).isWalkeable()){
			slots.add(this.nextSlot(slot, Direction.NORTH));
		}
		if (this.nextSlot(slot, Direction.EAST).isWalkeable()){
			slots.add(this.nextSlot(slot, Direction.EAST));
		}
		if (this.nextSlot(slot, Direction.WEST).isWalkeable()){
			slots.add(this.nextSlot(slot, Direction.WEST));
		}
		if (this.nextSlot(slot, Direction.SOUTH).isWalkeable()){
			slots.add(this.nextSlot(slot, Direction.SOUTH));
		}
		
		return slots;
	}

	public Slot farthestPath(Slot slot, Direction dir, int distance) {
		int moves = 0;
		Slot candidate = slot;
		boolean end = false;
		while(moves < distance & !end){
			if (this.nextSlot(candidate, dir).isWalkeable()){
				candidate =this.nextSlot(candidate, dir); 
			}
			else {
				end = true;
			}
			moves++;
		}
		return candidate;
	}
}
